/** author wanghua
 *  date   2014-6
*/
/* setting = {
  	queryFields=[
  		{columnName,columnLabel,elementType,dataType,operator,operatorLabel,value,unit,maxLength,width,visible,rowWrap,list:{url,data,valueKey,labelKey,multiple,addNull}}
  		//visible:always_show show hide list.data=[[value,label],[value,label],[value,label]]
    ]

  }
 */

(function($) {
	$.fn.dkQuery2 = function(setting){
		var self = this;
		var jqSelf = $(this);
		self.setting = $.extend({}, setting);
		self.id = $(this).attr("id");
		self.clickTagMenuList = 1;

		/**判断一个值是否在数组中**/
		var in_array = function(search,array) {
		    for(var i in array){
		        if(array[i]==search){
		            return true;
		        }
		    }
		    return false;
		};
		/**根据html的属性，构造查询项*/
		_initFields = function(){
			if(self.setting && self.setting.queryFields) return;
			var queryFields = [];
			$(".dk_pnl_query_field", jqSelf).each(function(i, element) {
				var queryField = {};
				var propName = $(element).data("propname");
				if(!propName){
					propName = $("input select", element).attr("name");
				}
				var propLabel = $(element).data("label");
				if(!propLabel){
					propName = $("label", element).text();
				}
				var fieldVisible = $(element).data("visible") || 'visible';
				
				var operator = $(element).data("operator");
				var dataType = $(element).data("datatype");
				queryField.columnName = propName;
				queryField.columnLabel = propLabel;
				queryField.operator = operator;
				queryField.dataType = dataType;
				queryField.visible = fieldVisible;
				queryFields.push(queryField);
			});
			self.setting.queryFields = queryFields;
		};

		/**检查定义的查询字段是否正确**/
		var _checkQueryField = function(queryField){
			var fieldCheckInfo = {};
			fieldCheckInfo.valid = true;
			fieldCheckInfo.message = "";

			var columnName = queryField.columnName;
			if(!columnName){
				fieldCheckInfo.valid = false;
				fieldCheckInfo.message += "<br>没有定义字段名称(columnName)";
			}


			var elementTypes = ['text','checkbox','radio','select'];
			var sqloperators = ['=','==','>','>=','<','<=','like','llike','leftlike','rlike','rightlike','in','between'];
			var dataTypes = ['string','varchar','number','double','float','int','integer','long','date','datetime','boolean','bool'];//

			if(!queryField.dataType) queryField.dataType = 'string';
			if(!queryField.elementType) queryField.dataType = 'text';
			if(!queryField.operator) queryField.operator = 'like';

			var dataType = queryField.dataType.toLowerCase();
			var elementType = queryField.elementType.toLowerCase();
			var sqloperator = queryField.operator.toLowerCase();
			if(dataType.indexOf("dt") == 0) dataType = dataType.substr(2);
			if(!in_array(dataType,dataTypes)){
				fieldCheckInfo.valid = false;
				fieldCheckInfo.message += "<br>字段"+columnName+"的数据类型错误：" + dataType;
			}
			if(!in_array(elementType,elementTypes)){
				fieldCheckInfo.valid = false;
				fieldCheckInfo.message += "<br>字段"+columnName+"的HTML元素类型错误：" + elementType;
			}
			if(!in_array(sqloperator,sqloperators)){
				fieldCheckInfo.valid = false;
				fieldCheckInfo.message += "<br>字段"+columnName+"的SQL查询操作符错误：" + sqloperator;
			}

			if(in_array(sqloperator,['like','llike','leftlike','rlike','rightlike']) &&
			   in_array(dataType,['number','double','float','int','integer','long','date','datetime','boolean','bool'])){
				fieldCheckInfo.valid = false;
				fieldCheckInfo.message += "<br>字段"+columnName+"的SQL查询操作符：" + sqloperator+"与数据类型"+dataType+"不匹配";
			}

			return fieldCheckInfo;
		};

		var _initQueryColumnsHtml = function(){//初始化查询条件输入面板

		};
		var _initColumnsMenu = function(){//初始化字段的右键弹出菜单

			var html = '<a href="javascript:void(0);"><i class="glyphicon glyphicon-list query-fields-list-btn"></i></a>';
			html += '<div id="menuColumnPopup" class="query-fields-list left" style="display: none; z-index: 1024; left: 213px; top: 29px;padding-top:5px;padding-bottom:10px;width:200px;background: rgb(255, 255, 255);margin-top:12px;box-shadow: rgb(238, 238, 238) 0px 1px 10px;border:1px solid rgb(226, 226, 226);"><table cellpadding="0" cellspacing="0"><tbody>';
			var jqMenuList = $("#columnList");
			if(jqMenuList.length==0){
				jqMenuList = $(".query-column-list", jqSelf);
			}
			var queryFields = self.setting.queryFields;
			if(!queryFields || queryFields.length == 0)return;

			for(var i=0; i < queryFields.length; ++i){
				var queryField = queryFields[i];
				if(!queryField)continue;
				if('always_show' == queryField.visible || 'alwaysVisible' == queryField.visible) continue;
				var checked1 = "checked";
				var checked_btn=" checked_btn";
				if('hide' == queryField.visible){
					checked1 = "";
					checked_btn="";
					var divName = "pnl_"+queryField.columnName;
					$("#"+divName).removeClass("inlineblock");
					$("#"+divName).addClass("hide");
				}
				var columnName = queryField.columnName;
				var columnLabel = queryField.columnLabel;
				html += '<tr><td class="l-column-left"><div class="check_box_btn'+checked_btn+'"><input type="checkbox" '+checked1+' columnName="'+columnName+'" class="l-checkbox query_menuitem_checkbox" columnindex="0"></div></td><td class="l-column-right">'+columnLabel+'</td></tr>';
			}
			html += '</tbody></table></div>';
			jqMenuList.append(html);
			jqMenuList.click(function(){
				var jqPopup = $("#menuColumnPopup");
				jqPopup.css("position","absolute");
				jqPopup.css("top",jqMenuList.offset().top + 23);
				jqPopup.css("left",jqMenuList.offset().left);
				jqPopup.css("display","block");
				self.clickTagMenuList = 2;
				jqPopup.focus();//这句话之后会马上触发$(document).click事件。所以使用self.clickTag来区别是否执行$(document).click里面的动作
			});
			$(".check_box_btn").click(function(){
				$(this).hasClass("checked_btn")?$(this).removeClass('checked_btn'):$(this).addClass("checked_btn");
			});
			//$(".query_menuitem_checkbox").bind("click",function(){alert('dddd');});
			$(".query_menuitem_checkbox").bind("click",onQueryMenuItemCheckChange);
			$('.query_menuitem_checkbox').on('ifChecked', function(event){
				onQueryMenuItemCheckChange2(event.target, true);
			});
			$('.query_menuitem_checkbox').on('ifUnchecked',  function(event){
				onQueryMenuItemCheckChange2(event.target, false);
			}); 
			
			$(document).click(function (e) {
				if(self.clickTagMenuList == 2){
					self.clickTagMenuList = 1;
					return;
				}
				var jqPopup = $("#menuColumnPopup");
				jqPopup.css("display","none");
			});
		};

		var onQueryMenuItemCheckChange = function(e){
			var jqChkbox = $(e.target);
			var visible1 = jqChkbox.prop("checked");
			onQueryMenuItemCheckChange2(e.target, visible1);
		}
		var onQueryMenuItemCheckChange2 = function(target, visible1){
			var jqChkbox = $(target);
			var visible1 = jqChkbox.prop("checked");
			var divName = "pnl_"+jqChkbox.attr("columnName");
			//console.log(divName);
			if(visible1){
				$("#"+divName).removeClass("hide");
				$("#"+divName).addClass("inlineblock");
			}else{

				$("#"+divName).removeClass("inlineblock");
				$("#"+divName).addClass("hide");
			}
			//console.log(jqChkbox.prop("checked"));
			//console.log(jqChkbox.attr("columnName"));
			//console.log(jqChkbox.html());
		};

		this.getQueryParams = function(){
			var queryFields = self.setting.queryFields;
			if(!queryFields || queryFields.length == 0)return;
			var queryParams = [];
			for(var i=0; i < queryFields.length; ++i){
				var queryField = queryFields[i];
				if(!queryField)continue;
				var columnName = queryField.columnName;
				var divName = "pnl_"+columnName;
				var queryValue = '';
				var op = queryField.operator || 'like';
				var dataType = queryField.dataType;
				if($("#"+divName).css('display') != 'none'){
					op = op.toLowerCase();
					if('eq' == op || 'equal' == op || '=' == op || '==' == op){
						queryValue = $("#"+columnName).val();
					}else if('>' == op || 'greater' == op){
						queryValue = $("#"+columnName).val();
					}else if('>=' == op || 'greaterandequal' == op){
						queryValue = $("#"+columnName).val();
					}else if('<' == op || 'less' == op){
						queryValue = $("#"+columnName).val();
					}else if('<=' == op || 'lessandequal' == op){
						queryValue = $("#"+columnName).val();
					}else if('like' == op || 'contains' == op){
						queryValue = $("#"+columnName).val();
					}else if('llike' == op || 'leftlike' == op){
						queryValue = $("#"+columnName).val();
					}else if('rlike' == op || 'rightlike' == op){
						queryValue = $("#"+columnName).val();
					}else if('in' == op || 'exists' == op){
						queryValue = $("#"+columnName).val();
						if(Object.prototype.toString.call(queryValue) === '[object Array]'){ //如果是数组
							queryValue = queryValue.join("|");
						}
					}else if('between' == op){
						var val = "";
						$("input[name='"+columnName+"'],select[name='"+columnName+"']").each(function(i){ //$("#"+columnName)
							var currVal = $(this).val();
							if(!currVal){
								currVal = "null";
							}
							val = val + "|" + currVal;
						});
						if(val != "|null|null"){
							queryValue = val.substr(1);
						}
					}
					var elementType = $("input[name='"+columnName+"']").attr('type');
					var multiValue = $("input[name='"+columnName+"']").length > 1;
					//if('radio' == queryField.elementType){
					if('radio' == elementType){
						queryValue = $("input[name='"+columnName+"']:checked").val();
					//}else if('checkbox' == queryField.elementType){
					}else if('checkbox' == elementType && !multiValue){
						var checked1 = $("#"+columnName).prop("checked");
						queryValue = checked1 ? 1 : 0;
					//}else if('checkbox-multi' == queryField.elementType){//checkbox-multi
					}else if('checkbox' == elementType && multiValue){
						var val = "";
						$("input[name='"+columnName+"']:checkbox").each(function(i){ //$("#"+columnName)
							if ($(this).prop("checked")){
								var currVal = $(this).val();
								if(currVal){
									val = val + "|" + currVal;
								}
							}
						});
						if(val && val.length>1){
							val = val.substr(1);
						}
						queryValue = val;
					}
					if(queryValue || 'checkbox' == elementType){//checkbox类型的，无论是否选中，都是查询条件
						var queryParam = {};
						queryParam.queryValue = queryValue;
						queryParam.operator = op;
						queryParam.dataType = dataType;
						queryParam.columnName = columnName;
						queryParam.columnExpression = queryField.columnExpression;
						queryParams.push(queryParam);
					}
				}
			}
			console.log(JSON.stringify(queryParams));
			return queryParams;
		};
		this.test = function(){
			//alert('123');
			//alert($(this).html());

		};
		//_init(this.queryPanelId);
		_initFields();
		_initQueryColumnsHtml();
		_initColumnsMenu();

		return self;
	};
})(jQuery);
